﻿namespace _08Net8AspNetCore_MiddleWare.Middlewares
{
    public class HtmlMiddleWare
    {
        public RequestDelegate next;

        public HtmlMiddleWare(RequestDelegate next)
        {
            this.next = next;
        }

        /// <summary>
        /// 获取html
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {

            string path = context.Request.Path.Value;
            if (path.Contains("html"))
            {
                await ResposeHtml(context);
            }
            else
            {
                await this.next(context);
            }

        }


        /// <summary>
        /// 获取html
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private static async Task ResposeHtml(HttpContext context)
        {
            // 1、设置文件类型
            context.Response.ContentType = "text/html";
            // 2、输出路径
            string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Index.html");
            // 3、读取文件内容
            var htmlContent = await File.ReadAllTextAsync(path);
            // 4、相应输出
            await context.Response.WriteAsync(htmlContent);
        }
    }


    /// <summary>
    /// html中间件扩展
    /// </summary>
    public static class HtmlMiddlewaresExtensions
    {
        public static IApplicationBuilder UseHtml(this IApplicationBuilder app)
        {
            app.UseMiddleware<HtmlMiddleWare>();
            return app;
        }
    }
}
